<!-- 新增部门 -->
<template>
  <Modal class="add_form" v-model="modal" :title="`${depId ? '编辑' : '创建新'}部门`" :mask-closable="false" draggable sticky scrollable
      @on-cance="cancel" @on-visible-change="cancel" width="800px">
      <Form ref="formEl" :model="formData" :rules="rules" label-position="top">
          <div class="flex_form_item">
              <FormItem label="部门名称" prop="name">
                  <Input v-model="formData.name" placeholder="请输入部门名称" clearable></Input>
              </FormItem>
          </div>
          <div class="flex_form_item">
              <FormItem label="上级机构" prop="parent">
                  <el-tree-select v-model="formData.parent" check-strictly default-expand-all placeholder="请选择上级机构" :data="organData" :props="{label: 'name', value: 'id'}">
                  </el-tree-select>
              </FormItem>
          </div>
      </Form>
      <template #footer>
          <Button @click="cancel">取消</Button>
          <Button type="primary" @click="submit">确定</Button>
      </template>
  </Modal>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { organCreate, organDetail, organUpdate, organList } from '@/api/modules/department'
import { listToTree } from '@/util';
const emit = defineEmits(['cancel', 'submit']);

// 是否打开弹窗
const modal = true;

// 加载
const loading = ref(true)

// 表单元素ref
const formEl = ref(null);

// 表单字段
const formData = ref({
  name: '',
  parent: ''
})

// 表单校验条件
const rules = ref({
  name: [{ required: true, message: '请填写部门名称', trigger: 'blur' }],
  parent: [{ required: true, message: '请选择上级机构', trigger: 'change' }],
})

// 获取上级机构数据(部门)
const organData = ref([
  {
    name: '组织机构',
    id: '0',
    children: []
  }
]);

const getOrganList = async () => {
  const { data } = await organList()
  organData.value[0].children = listToTree(data);
}

// 初始化表单
const depId = ref(undefined);
const isUpdate = ref(false);
const initDialog = async(organ, type) => {
  formEl.value.resetFields();
  if (type == 'edit' && !!organ.id) {
    isUpdate.value = true;
    depId.value = organ.id;
    formData.value.name = organ.name;
    formData.value.parent = organ.parent;
    return
  }
  isUpdate.value = false;
  formData.value.parent = organ.id || '0';
}

/**
* 提交表单
*/
const submit = async () => {
  let valid = await formEl.value.validate((valid, fild) => valid ? valid : fild);
  if (!valid) return;
  loading.value = true;
  try {
    await (isUpdate.value ? organUpdate : organCreate)({data: {...formData.value, id: isUpdate.value ? depId.value : undefined }});
    emit('submit')
  }catch (error) {
    console.log(error)
  }
}


/**
* 取消表单
*/
const cancel = () => {
  emit('cancel');
}
/**
* 加载数据
*/
onMounted(() => {
  getOrganList()
})

defineExpose({
  initDialog
})

</script>